<template>
  <div>
    <div style="height: 100%;width: 200rpx">
      <u-popup :show="show" :round="10" mode="top" @close="close">
        <view>
          <!--          输入框，评论一条-->
          <div style="padding: 20rpx 0;width: 100%" class="showInputCClass">
            <div style="float: left;width: 80%">
              <textarea placeholder="想说什么就说什么叭- -" @blur="inputBlur" :focus="inputFocus" :auto-height="true"
                        :show-confirm-bar="fal-se" maxlength="1500" v-model="zyComment.content" class="post-txt"></textarea>
            </div>
            <div style="float: right">
              <view style="width: 120rpx;height: 110rpx">
                <u-button type="primary" text="确定" @click="sendComment"></u-button>
              </view>
            </div>
          </div>
        </view>
      </u-popup>
    </div>
    <!-- 聊天区   -->
    <div v-for="(comApp , index) in commentsAppExternal" :key="index">
      <div  @click="toggleInnerBox(index)">
        <!--      添加一条数据，悬浮-->
        <div>
          <!-- 在手机左下角添加图标 -->
          <view class="icon-container" @click="jumpDetailed">
            <u-icon name="plus" size="20" color="#fff"></u-icon>
          </view>
          <!--        </el-button>-->
        </div>
        <div class="container">
          <div class="column avatar">
            <!-- 这里放置头像 -->
            <u-avatar :src="comApp.zyOwner.ownerPortrait" size="50" shape="circle"></u-avatar>
          </div>
          <div class="column1">
            <span class="column1-name-span">{{ comApp.zyOwner.ownerNickname }}</span>
            <!--          删除一条动态-->
              <span style="float: right"><u-icon show="{{comApp.zyOwner.ownerId === uni.getStorageSync('ownerId')}}" name="trash" size="28"
                                                 @click="submit(comApp.interactionId)"></u-icon></span>
            <div class="contentText">
              <span>{{ comApp.content }}</span>
              <!-- 显示多张图片 -->
              <div style="margin-top: 30rpx;">
                <u-grid :col="3">
                  <u-grid-item v-for="(image, imgIndex) in comApp.someImages" :key="imgIndex">
                    <div class="image-container">
                      <img :src="image" alt="被分享的图片" @click="clickImg(comApp.someImages, imgIndex)" :class="{ zoomed: isZoomed }"
                           style="width: 170rpx; height: 170rpx;">
                    </div>
                  </u-grid-item>
                </u-grid>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div class="column2">
        <div style="margin: 0 30rpx 30rpx 50rpx">
          <span style="font-size: 26rpx ;color: #6d6d72">{{ comApp.createTime }}</span>
          <span style="float: right">
          <u-icon :name="'判断条件' === '' ? 'chat-fill' : 'chat'" size="30" @click="open(comApp.interactionId)"
                  style="margin-bottom: 30rpx"></u-icon>
          </span>
          <!--            点赞-->
          <span style="float: right">
          <u-icon :name="comApp.isLiked ? 'thumb-up-fill' : 'thumb-up'" size="30"
                  @click="likeComment(comApp.interactionId,index,comApp.isLiked)"
                  style="margin-bottom: 30rpx"></u-icon>
          </span>
          <span style="font-size: 30rpx;color: blue;float: right">{{comApp.likeCount === null?0:comApp.likeCount}}</span>
        </div>
        <!--      隐藏框-->
        <view class="outer-box">
          <div v-if="innerBoxesVisible[index]" class="inner-box" >
            <!--  嵌套盒子        -->
            <div v-if="nComListData.id === comApp.interactionId" v-for="(nComListData , index2) in nestedCommentsListData"  @click="open(comApp.interactionId)"
                 :key="index2" @click="" style="margin-left: 30rpx ; margin-top: 10rpx">
              <div class="column avatar" style="margin-right: 50rpx">
                <!-- 这里放置头像 -->
                <u-avatar :src="nComListData.data.ownerPortrait" size="50" shape="circle"></u-avatar>
              </div>
              <div class="column1">
                <span class="column1-name-span">{{ nComListData.data.ownerNickName }}</span>
                <span class="column1-name-span" v-if="nComListData.data.parentId !== null && nComListData.data.parentId !== '-1'">-回复-{{nComListData.parentName}}</span>
                <div class="contentText">
                  <span>{{ nComListData.data.content }}</span>
                </div>
              </div>
              <div class="column2">
                <div style="margin: 0 30rpx 30rpx 30rpx">
                  <span style="font-size: 26rpx">{{ nComListData.data.createTime }}</span>
                  <span style="float: right"><u-icon @click="toggleInnerBox(index2)"  size="30"></u-icon></span>
                </div>
                <u-line color="#8f8f94" />
              </div>
            </div>
          </div>
        </view>
        <u-line color="#8f8f94" />
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      bgColor: '#001f3f', // 导航栏颜色
      commentsAppExternal: [], // 所有评论
      nestedCommentsListData: [], // 嵌套评论内容
      itemList: [1, 2, 3], // 或其他任意标识符作为循环的数据源
      innerBoxesVisible: [], // 控制每个内部盒子的显示与隐藏
      likes: [], // 所有的评论点赞
      likeList:[], // 点赞列表
      isZoomed: false,
      show: false, // 显示弹出输入框
      // 默认输入框获得焦点
      inputFocus: true,
      /*输入框*/
      value: '',
      /*按钮*/
      disabled: true,
      zyComment:{
        commentId:'',
        createBy:'',
        updateBy:'',
        createTime:'',
        updateTime:'',
        content:'', // 评论内容
        parentId:'',
        delFlag:'',
        interactionId:'', // 目标评论id
        userId:'',
        remark:'',
        rootId:'', // 当前登录用户id

        isLiked:'',// 判断点赞
      },
      zyLike: {
        likeId:'',
        interactionId:'',
      }
    }
  },
  created() {
    this.initInnerBoxesVisible();
  },
  methods: {
    async submit(iId) {
      uni.showModal({
        title: '提示：',
        content: '请确认是否要删除?',
        success: (res) => {
          if (res.confirm) {
            this.deleteComment(iId);
            // console.log('确定');
            //TODO
          } else if (res.cancel) {
            // console.log('取消');
            this.commentsPage()
            //TODO
          }
        }
      });
    },
    /*删除一条动态*/
    async deleteComment(id) {
      console.log("删除的id" , id)
      await this.$http.delete('/uni-app/zyCommunityInteraction/'+ id)
      // 刷新当前页面
      this.commentsPage()
    },
    /*发送一条评论*/
    sendComment() {
      this.zyComment.userId = uni.getStorageSync('ownerId')
      this.zyComment.createBy = uni.getStorageSync('ownerId')
      this.zyComment.delFlag = '0'
      this.$http.put('/uni-app/zyComment/',this.zyComment)
      // 刷新当前页面
      this.commentsPage()
    },
    /*点赞+图标改变*/
    async likeComment(zyLike,index,isL) {
      if (!isL){
        console.log("点赞了一下")
        /*没有点赞*/
        /*执行添加一个点赞*/
        await this.$http.put('/uni-app/like/',zyLike)
      }else {
        console.log("取消了点赞")
        /*取消点赞*/
        await this.$http.delete('/uni-app/like/'+ zyLike)
      }
      this.commentsPage(!isL,zyLike)
    },
    /*获取当前是否有改点赞*/
    thisIsLike(id){
      for (let i = 0; i < this.likeList.length; i++) {
        if (this.likeList[i].interactionId === id){
          return true;
        }
        if (this.likeList.length ===i+1){
          return false;
        }
      }
    },
    /*显示所有记录*/
    async commentsPage(value,zyLike) {
      await this.$http.post('/uni-app/zyCommunityInteraction').then(result => {
            let someImages = '';
            result.data.data.forEach((item ) => {
              if (item.images.includes(",")){
                const images = item.images.split(',');
                someImages = images.map((image) => {
                  return image.trim();
                });
                item.someImages = someImages;
                /*将内嵌值放入*/
                this.nestedCommentsList(item.interactionId)
              }
              item.isLiked = this.thisIsLike(item.interactionId);
            });
            this.commentsAppExternal.images = someImages;

            this.commentsAppExternal = result.data.data;
            // 按照 createTime 进行降序排序
            this.commentsAppExternal.sort((a, b) => {
              const dateA = new Date(a.createTime.replace(/-/g, "/")).getTime();
              const dateB = new Date(b.createTime.replace(/-/g, "/")).getTime();
              return dateB - dateA;
            });
            for (let index = 0; index < this.commentsAppExternal.length; index++) {
              if ( this.commentsAppExternal[index].interactionId === zyLike){
                this.commentsAppExternal[index].isLiked = value
                break;
              }
            }
          });
    },
    /*被嵌套评论*/
    async nestedCommentsList(interactionId){
      await this.$http.get('/uni-app/'+ interactionId).then(result => {
        if (result.data.data.length !== 0){
          result.data.data[0].zyComments.forEach(((item) => {

            this.nestedCommentsListData.push({
              id: interactionId,
              data: item,
              parentName: ''
            })
          }))
          this.getOwnerNameByCommentId();
          result.data.data[0].zyComments.forEach((item) => {
            const images = item.images.split(',');
            const someImages = images.map((image) => {
              return image.trim();
            });
            item.someImages = someImages;
          });
        }
      })
    },
    /*被回复者*/
    async getOwnerNameByCommentId(){
      for (let i = 0; i < this.nestedCommentsListData.length; i++) {
        await this.$http.get('/uni-app/zyOwner/'+ this.nestedCommentsListData[i].data.parentId).then(result => {
          this.nestedCommentsListData[i].parentName = result.data.data;
        })
      }
    },
    async initInnerBoxesVisible() {
      this.innerBoxesVisible = new Array(this.itemList.length).fill(false); // 初始化内部盒子的显示与隐藏状态
    },
    /*多图片显示*/
    /*图片显示与否*/
    clickImg(images, index) {
      wx.previewImage({
        urls: images, //需要预览的图片http链接列表，多张的时候，url直接写在后面就行了
        current: images[index], // 当前显示图片的http链接，默认是第一个
        success: function (res) {},
        fail: function (res) {},
        complete: function (res) {},
      });
    },
    /*获取images中的image*/
    oneImages(images, index) {
      this.commentsAppExternal[index].someImages = images.split(',').map((image) => {
        return image.trim();
      });
    },
    /*点击显示子评论*/
    toggleInnerBox(index) { // index是一个索引
      /*子评论逻辑*/
      // 写好添加图片
      // 实现展示图片
      // 《——写子评论逻辑——》
      /*响应式地切换显示与隐藏状态*/
      this.$set(this.innerBoxesVisible, index, !this.innerBoxesVisible[index]);
    },
    /*输入框*/
    change(e) {
      console.log('change', e);
    },
    open(iId) {
      console.log("我是程铭",iId)
      this.zyComment.interactionId = iId;
      this.zyComment.parentId = '-1';
      this.show = true
      // console.log('open');
    },
    close() {
      this.show = false
      // console.log('close');
    },
    // 文字内容
    inputBlur(event) {
      this.inputCursor = event.detail.cursor;
      this.inputFocus = false;
    },
    /*跳转详细*/
    jumpDetailed() {
      uni.navigateTo({
        url: '/pages/community/addCommentMe', // 跳转的页面路径
      });
    },
  },
  mounted() {
    this.commentsPage();

    this.$http.post('/uni-app/like').then(result => {
      this.likeList = result.data.data;
    });
  },
}
</script>

<style scoped lang="scss">
div {
  //border: 1px solid red;
}

/*评论样式*/
.mall-pintuan-head > view image {
  width: 12rpx;
  height: 20rpx;
  margin-left: 12rpx;
}

.container {
  margin: 10px 10px;
  display: flex;
}

.column {
  flex: 2;
  flex-direction: column;
}

.column1 {
  margin-left: 20rpx;
  flex: 9;
  flex-direction: column;
}

.column2 {

}

.column1-name-span {
  color: #173294;
  font-size: 32rpx;
  font-weight: bold;
}

.avatar {
  height: 100rpx;
  width: 45rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  float: left;
}

.contentText {
  flex: 1;
  padding-top: 30rpx
}

/*下拉框*/
.outer-box {
  margin: 20px;
}
.inner-box {
  padding: 10px;
  background-color: #f0f0f0;
  margin-top: 40px;
}
.inner-box-copy {
  padding: 10px;
  background-color: #e0e0e0;
  margin-top: 10px;
}
/*图片*/
.image-container {
  position: relative;
}

img {
  cursor: pointer;
  transition: transform 0.3s ease-in-out;
  width: 120rpx;
  height: 120rpx;
}

.zoomed {
  transform: scale(2);
}
/*显示多张图片*/
.grid-text {
  font-size: 35rpx;
  margin-top: 4rpx;
}
.content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}
.logo {
  height: 200rpx;
  width: 200rpx;
  margin-top: 200rpx;
  margin-left: auto;
  margin-right: auto;
  margin-bottom: 50rpx;
}
/*悬浮按钮~添加*/
.float-button {
  position: fixed;
  bottom: 50px;
  right: 50px;
  text-align: center;
}

.icon-container {
  position: fixed;
  top: 600px;
  right: 30px;
  z-index: 999;
  background-color: #007aff;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  width: 40px;
  height: 40px;
}

.icon-container u-icon {
  margin-top: 2px; /* 调整图标位置 */
}

.icon-container:hover {
  background-color: #0056b3;
}
</style>
